package com.team.web;


import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.team.dao.FileDao;
import com.team.dao.FolderDao;
import com.team.entity.FileSingle;
import com.team.entity.Folder;
import com.team.entity.User;
import com.team.util.Const;
import com.team.util.TUtil;


public class FileServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
		
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String method = request.getParameter("_m");
		
		if("save".equals(method)){
			save(request,response);
		}else if("select".equals(method)){
			select(request,response);
			
		}
		
	}

	private void select(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("folderId");
		int folderId = Integer.parseInt(id);
		
	
		
		FolderDao fd = new FolderDao();
		Folder folder  = fd.selectFolder(folderId);
		if(folder != null){
			FileDao filedao = new FileDao();
			List<FileSingle> list = filedao.selectAllByFolderId(folderId);
			if(list != null){
				HttpSession session = request.getSession();
				session.setAttribute("folder",folder);
				session.setAttribute(Const.SESSION_FILEList, list);
				request.getRequestDispatcher("/WEB-INF/views/singlefile.jsp").forward(request, response);
				//response.sendRedirect("singlefile.jsp");
				return ;
			}else {
				System.out.println("list is null");
			}
		}else {
			System.out.println("folder find error");
			
		}
		
		
		
		
		 
	}

	private void save(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		if(request.getMethod().equalsIgnoreCase("get")){
			toFilePage(request,response);
		}else {
			upLoad(request,response);
			
		}
		
		
	}

	private void upLoad(HttpServletRequest request, HttpServletResponse response) {
		String folderId = request.getParameter("folderId");
		int id = Integer.parseInt(folderId);
		System.out.println("folderId"+folderId);
		
		FolderDao fd = new FolderDao();
		
		Folder folder = fd.selectFolder(id);
		if(folder != null){
			
			String fileName = null;
			String name  = null;
			ServletContext ctx = getServletContext();
			String serverPath = ctx.getRealPath("/");
			
			//鏂囦欢鐨勪笂浼犺矾寰�
			File file = new File(serverPath + folder.getFiletypename());
			
			//涓存椂鏂囦欢璺緞
			File tempFile = new File(serverPath + "temp");
			
			if(!file.exists()) {
				file.mkdir();
			}
			
			if(!tempFile.exists()) {
				tempFile.mkdir();
			}
			
			if(ServletFileUpload.isMultipartContent(request)) {
				DiskFileItemFactory factory = new DiskFileItemFactory(); 
				//璁剧疆缂撳啿鍖哄ぇ灏�
				factory.setSizeThreshold(1024*10); 
				//璁剧疆涓存椂鏂囦欢澶�
				factory.setRepository(tempFile); 
				
				ServletFileUpload fileUpload = new ServletFileUpload(factory); 
				fileUpload.setSizeMax(1024 * 1024);
				
				try {
					List<FileItem> fileItems = fileUpload.parseRequest(request);
					
					for(FileItem item : fileItems) {
						if(item.isFormField()) {
							
							name = item.getFieldName();
							String value = item.getString();
							System.out.println(name + " 鈫�" + value);
							
						} else {
							//涓婁紶
							fileName = item.getName();
							
							long fileSize = item.getSize();
							System.out.println("鏂囦欢鍚�" + fileName + "\t鏂囦欢澶у皬:" + fileSize);
							//save file in t_file 
							HttpSession session = request.getSession();
							User user = (User) session.getAttribute(Const.SESSION_USER);
							FileDao dao = new FileDao();
							FileSingle fs = new FileSingle();
							fs.setCreateTime(TUtil.getNow());
							fs.setFilenNme(fileName);
							fs.setFileSize(fileSize);
							fs.setFileTypeId(id);
							fs.setName(name);
							fs.setUserId(user.getId());
							
							
							int num = dao.save(fs);
							if(num > 0){
								response.sendRedirect("file.jspx?_m=select&folderId="+id);
								return ;
							}else {System.out.println("save file error");}
							
							item.write(new File(file,fileName));
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				System.out.println("鏈缃甧nctype灞炴�");
			}
		}else {
			System.out.println("error");
		}
	}

	private void toFilePage(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException  {
		request.getRequestDispatcher("/WEB-INF/views/newfile.jsp").forward(request, response);
		//response.sendRedirect("newfile.jsp");
		return ;		
	}



}
